
import 'dart:async';
import 'dart:io';

import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/pages/im/util/media_util.dart';
import 'package:flare_flutter/flare_actor.dart';
import 'package:flutter/material.dart';

class CommAlertVoiceWidget extends StatelessWidget {
  final Function(String voicepath, int duration) onFinish;
  final Function onCancel;

  /// 需要显示已经录制完成的状态用.
  final String path;
  final int duration;
  final int minDuration; // 最小录制音频
  ///

  String _voicepath;
  int _duration = 0;
  CommAlertVoiceWidget({Key key, this.path, this.minDuration, this.duration, this.onFinish, this.onCancel}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final bottom = MediaQuery.of(context).padding.bottom;
    return SafeArea(
          bottom: false,
          child: Container(
            height:180 + bottom,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(topLeft: const Radius.circular(10), topRight: const Radius.circular(10))
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    GestureDetector(
                      onTap: (){
                        if(onCancel != null) onCancel();
                        MediaUtil.instance.stopPlayAudio();
                        Navigator.of(context).pop();
                      },
                      child: Container(
                        color: Colors.white,
                        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                        child: Text("取消", style: instanceTextStyle(14, APP_font_black),),
                      )
                    ),
                    GestureDetector(
                      onTap: (){
                        if(onFinish != null) onFinish(_voicepath, _duration);
                        MediaUtil.instance.stopPlayAudio();
                        Navigator.of(context).pop();
                      },
                      child: Container(
                        color: Colors.white,
                        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                        child: Text("完成", style: instanceTextStyle(14, APP_font_black),),
                      ),
                    )
                  ],
                ),
                Expanded(child: XCommentVoiceWidget(
                  path: path,
                  duration: duration,
                  minDuraion: minDuration,
                  onRecordFinish: (String voicepath, int duration){
                    _voicepath = voicepath;
                    _duration = duration;
                },)),
              ],
            )
          ),
        );
  }
}

class XCommentVoiceWidget extends StatefulWidget {

  final Function(String voicepath, int duration) onRecordFinish;
  final String path; // 需要显示录制完成时候显示
  final int duration;
  final int minDuraion;
  _XCommentVoiceWidgetState _state;

  XCommentVoiceWidget({Key key, this.minDuraion, this.onRecordFinish, this.path, this.duration}) : super(key: key);

  void reset() {
    _state._reset();
  }
  @override
  _XCommentVoiceWidgetState createState() => _state = _XCommentVoiceWidgetState();
}

class _XCommentVoiceWidgetState extends State<XCommentVoiceWidget> {

  bool isselected = false;
  bool isrecord = false;
  File _file;
  bool isupadte = false;
  Timer _timer;
  int voiceLength = 30;
  int recordLength = 0; // 录制时长
  String voicestr = "00:00";
  bool istestPlay = false; // 录完音之后的试听
  int minDuration = 5;

  @override
  void initState() {
    super.initState();
    minDuration = widget.minDuraion ?? 5; // 最小录制
    if(widget.duration != null && widget.path != null) {
      recordLength = widget.duration;
      isrecord = true;
      final t = widget.duration.toString();
      if(t.length == 1) {
        voicestr = "00:0" + t;
      } else {
        voicestr = "00:" + t;
      }
    }
  }

  @override
  void dispose() {
    _stopTimer();
    print("录音widget被释放");
    super.dispose();
  }

  void _reset() {
    voiceLength = 30;
    setState(() {
      isrecord = false;
      isselected = false;
      istestPlay = false;
      voicestr = "00:00";
    });
    MediaUtil.instance.stopPlayAudio();
    _deleteFile();
  }

   _beginTimer() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if(voiceLength == 0) {
        AlertTool.showToast("最多只能录30秒哦!");
        _recordFinish();
      } else {
        voiceLength -= 1;
        int t = 30 - voiceLength;
        _changeTime(t);
      }
    });
  }

  // 播放录音
  _playTimer(int maxtime) {
    setState(() {
      istestPlay = true;
    });
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if(maxtime == -1) {
        setState(() {
          istestPlay = false;
        });
        _stopTimer();
        _changeTime(maxtime);
      } else {
        maxtime -= 1;
        _changeTime(maxtime);
      }
    });
  }

  // 录音、播放时间格式化
  void _changeTime(int time) {
    final t = time.toString();
    if(t.length == 1) {
      setState(() {
        voicestr = "00:0" + t;
      });
    } else {
      setState(() {
        voicestr = "00:" + t;
      });
    }
  }

  // 停止录音
  _stopTimer() {
    voiceLength = 30;
    _timer?.cancel();
    _timer = null;
  }

  // 删除资源
  _deleteFile() {
    if(_file == null) return;
    String path = MediaUtil.instance.getCorrectedLocalPath(_file.path);
    File file = File(path);
    if (file != null && file.existsSync()) {
      file.deleteSync();
    }
  }

  void _recordFinish() {
    int t = 30 - voiceLength;
    _stopTimer();
    MediaUtil.instance.stopRecordAudio((path, duration){
      _file = File(path);
      if(widget.onRecordFinish != null) widget.onRecordFinish(MediaUtil.instance.getCorrectedLocalPath(path), duration);
      recordLength = t;
      setState(() {
        isrecord = true;
      });
      _changeTime(t);
    });
  }

  @override
  Widget build(BuildContext context) {

    return Container(
      alignment: Alignment.center,
      child: Stack(
        children: [
          Offstage(
            offstage: isrecord,
            child: Column(
              children: [
                Offstage(
                  offstage: !isselected,
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 7),
                    margin: const EdgeInsets.only(top: 12),
                    decoration: BoxDecoration(
                      color: APP_main_color,
                      borderRadius: BorderRadius.circular(20)
                    ),
                    child: Text(voicestr, style: instanceTextStyle(14, Colors.white),),
                  ),
                ),
                GestureDetector(
                  onLongPress: (){
                    setState(() {
                      isselected = !isselected;
                    });
                    
                    MediaUtil.instance.startRecordAudio();
                    _beginTimer();
                  },
                  onLongPressUp: (){
                    if(isrecord) return;
                    int t = 30 - voiceLength;
                    print("$recordLength");
                    if(t < minDuration) {
                      setState(() {
                        isrecord = false;
                        isselected = false;
                        voicestr = "00:00";
                      });
                      _stopTimer();
                      AlertTool.showToast("录音时间不能少于$minDuration");
                    } else {
                      _recordFinish();
                    }
                  },
                  child: Container(
                    color: Colors.white,
                    padding: EdgeInsets.only(top: isselected ? 10 : 48),
                    child: Image.asset(isselected ? "assets/huatong2.png" : "assets/huatong1.png"),
                  ),
                )
              ],
            ),
          ),
          Offstage(
            offstage: !isrecord,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                GestureDetector(
                  onTap: (){
                    _playTimer(recordLength);
                    MediaUtil.instance.startPlayAudio(_file.path);
                  },
                  child: FlrTestPlatWidget(
                    margin: const EdgeInsets.symmetric(horizontal: 110),
                    padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 5),
                    isplay: istestPlay, duration: int.parse(voicestr.substring(3)) == -1 ? recordLength : int.parse(voicestr.substring(3))
                  )
                ),
                SizedBox(height: 33,),
                GestureDetector(
                  onTap: _reset,
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 6),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20),
                      border: Border.all(color:APP_divider_color, width: 0.5)
                    ),
                    child: Text("重录", style: instanceTextStyle(14, APP_font_black),),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }
}

class FlrTestPlatWidget extends StatelessWidget {

  final bool isplay;
  final int duration;
  final EdgeInsets margin;
  final EdgeInsets padding;
  final double width;

  const FlrTestPlatWidget({Key key, this.isplay, this.duration, this.margin, this.padding, this.width}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
      width: width,
      margin: margin,
      padding: padding,
      decoration: BoxDecoration(
        color: APP_main_color,
        borderRadius: BorderRadius.circular(20)
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          // Image.asset("assets/bofang22.png", width: 10.w, height: 18.h,),
          Image.asset(isplay ? "assets/bofang_pause.png" : "assets/bofang22.png", width: 10.w, height: 18.h,),
          // Image.asset("assets/yuyin22.png"),
          Container(
            height: 25.h,
            width: 67.5.w,
            padding: const EdgeInsets.symmetric(vertical: 5),
            child: FlareActor("assets/flr/record.flr", alignment:Alignment.center, fit:BoxFit.fitWidth, animation:isplay ? "record" : "stop")
          ),
          Text("$duration‘‘", style: instanceTextStyle(14, Colors.white),)
        ],
      ),
  );
  }
}